const Koa = require('koa')
const app = new Koa()
const bodyParser = require('koa-bodyparser')
app.use(bodyParser())

const fs = require('fs')

const multer = require('koa-multer') //加载koa-multer模块

const cors = require('koa2-cors')

app.use(
  cors({
    origin: function (ctx) {
      return 'http://was666.gitee.io' //只允许这个域名的请求
        //  return '*'; // 允许来自所有域名请求
    },
    maxAge: 60, //指定本次预检请求的有效期，单位为秒。
    credentials: true, //是否允许发送Cookie
    allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], //设置所允许的HTTP请求方法'
    allowHeaders: ['Content-Type', 'Authorization', 'Accept'], //设置服务器支持的所有头信息字段
    exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'] //设置获取其他自定义字段
  })
)

//文件上传
//配置
var storage = multer.diskStorage({
  //文件保存路径
  destination: function (req, file, cb) {
    cb(null, 'public/uploads/')
  },
  //修改文件名称
  filename: function (req, file, cb) {
    var fileFormat = file.originalname.split('.')
    cb(null, Date.now() + '.' + fileFormat[fileFormat.length - 1])
  }
})
//加载配置
var upload = multer({ storage: storage })

const Router = require('koa-router')
const router = new Router()

function htmlvg() {
  return new Promise((resolve, reject) => {
    fs.readFile('./upload.html', (err, data) => {
      if (err) throw err
      let html = data.toString()
      resolve(html)
    })
  })
}

router.get('/', async function (ctx, next) {
  ctx.body = await htmlvg()
  next()
})

router.post('/upload/miniShop', upload.single('file'), async (ctx, next) => {
  ctx.body = {
    success: true,
    filename: ctx.req.file.filename, //返回文件名
    data: {
      src: 'http://img.aseditor.fun/uploads/' + ctx.req.file.filename //拼接地址
    }
  }
  next()
})

app.use(router.routes()).use(router.allowedMethods())

app.listen(3000)
console.log('[demo] start-quick is starting at port 3000')
